package cn.edu.scau.cmi.chenmiaopeng.hibernate.dao;
import java.util.List;
import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.edu.scau.cmi.chenmiaopeng.hibernate.domain.Student;
import cn.edu.scau.cmi.chenmiaopeng.hibernate.domain.Teacher;
import cn.edu.scau.cmi.chenmiaopeng.hibernate.factory.HibernateSessionFactory;
public class StudentDAO{
    private Session session;
    private Transaction transaction;
    private static final Logger log = LoggerFactory.getLogger(StudentDAO.class);
	// property constants
	public static final String NAME = "name";
	public static final String NUMBER = "number";
	private String result = null;
	public String getResult() {
	    return result;	
	}
	public void save(Student transientInstance) {  //新建学生 x
		session = HibernateSessionFactory.getSession();
		log.debug("saving Student instance");
		try {
			transaction = session.beginTransaction();  //增删改必须要用transaction
			session.save(transientInstance);  //getSession()不行
			log.debug("save student successful!");
			result = "save student successful!";
			transaction.commit();
			session.close();
		} catch (RuntimeException re) {
			log.error("save student failed!", re);
			result = "save student failed!";
			throw re;
		}
	}
	
	public void updateStudentByName(long oldId, String newName) {
		session = HibernateSessionFactory.getSession();
		log.debug("update student instance");
		try {
			//使用session.update()进行更新（不行）
			transaction = session.beginTransaction();
			Student instance = (Student)session.get("cn.edu.scau.cmi.chenmiaopeng.hibernate.domain.Student",oldId);
			if(instance==null) {
				result = "找不到该学生，请核实！";
				return;
			}
            instance.setName(newName);
			session.update(instance);  //session.update(object o) 对对象进行更新
			transaction.commit();  //直接commit即可保存
			session.close();
			log.debug("update student name successful!");
			result="update student name successful!";
		} catch (RuntimeException re) {
			log.error("update student name failed!", re);
			result="update student name failed!";
			throw re;
		}
	}
//	instance.setTeacher(tutor);
//	Teacher tutor = (Teacher)session.get("cn.edu.scau.cmi.chenmiaopeng.hibernate.domain.Teacher", 1L);  //主键类型要搭配，java.lang.Long
	public void updateStudentIdAndName(long oldId, long newId, String newName) {
		session = HibernateSessionFactory.getSession();
		log.debug("update student instance");
		try {
			//使用session.update()进行更新（不行）
			transaction = session.beginTransaction();
			Student instance = (Student)session.get("cn.edu.scau.cmi.chenmiaopeng.hibernate.domain.Student",oldId);
			if(instance==null) {
				result = "找不到该学生，请核实！";
				return;
			}
//			Student cloStu = (Student)instance.clone();
//			cloStu.setId(newId);
//			cloStu.setName(newName);
			
//			session.delete(instance);
//			Student newOne = new Student();
//			newOne.setId(newId);
//			newOne.setName(newName);
//			session.save(newOne);  //session.update(object o) 对对象进行更新  此时有两个除id不同以外其他属性相同的对象在数据库表中
			
			session.createSQLQuery("update student set id="+newId+", name='"+newName+"' where id = "+oldId).executeUpdate();
			//并不需要transaction,直接执行sql语句
			
//			getHibernateTemplate();
			transaction.commit();  //直接commit即可保存
			session.close();
			log.debug("update student successful!");
			result="update student successful!";
		} catch (RuntimeException re) {
			log.error("update student failed!", re);
			result="update student failed!";
			throw re;
		}
	}
	public void delete(Student persistentInstance) {  //删除学生  x
		session = HibernateSessionFactory.getSession();
		transaction = session.beginTransaction();
		log.debug("deleting Student instance");
		try {
			session.delete(persistentInstance);  //getSession()
			log.debug("delete student successful!");
			result = "delete student successful!";
			transaction.commit();
			session.close();
		} catch (RuntimeException re) {
			log.error("delete student failed!", re);
			result = "delete student failed!";
			throw re;
		}
	}
	//其实选择和修改指导学生没有本质的差异  这里没有成功，可能因为授权问题
	public void addTutor(long teacherId,long studentId) {
//		session = HibernateSessionFactory.getSession();
//		transaction = session.beginTransaction();
		log.debug("add Tutor for Student instance");
		try {
            Student addStu = findById(studentId);
			TeacherDAO teacherDAO = new TeacherDAO();
			teacherDAO.addStudent(teacherId, addStu);
			log.debug("add tutor successful!");
			result = "add tutor successful!";
		} catch (RuntimeException re) {
			log.error("add tutor failed!", re);
			result = "add tutor failed!";
			throw re;
		}
	}
	public void alterTutor(long teacherId,long studentId) {  //这里再增加学生没有导师，则抛出学生没有导师异常，要先有导师才能修改导师
		session = HibernateSessionFactory.getSession();
		transaction = session.beginTransaction();
		TeacherDAO teacherDAO = new TeacherDAO();
		log.debug("alter Tutor for Student instance");
		try {
			Student stu = findById(studentId);
			//删除原来的导师：
			Teacher originalTea = stu.getTeacher();
			teacherDAO.deleteStudent(originalTea.getId(), stu);
			//添加新的导师：
			teacherDAO.addStudent(teacherId, stu);
			log.debug("alter tutor successful");
			transaction.commit();
			session.close();
		} catch (RuntimeException re) {
			log.error("alter tutor failed", re);
			throw re;
		}
	}
    
	
	public Student findById(java.lang.Long id) {  //查询学生
		session = HibernateSessionFactory.getSession();
		log.debug("getting Student instance with id: " + id);
		try {
			Student instance = (Student)session.get("cn.edu.scau.cmi.chenmiaopeng.hibernate.domain.Student",id);  //这里改回自己的名字
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}
	public List findAll() {  //查询所有学生
		session = HibernateSessionFactory.getSession();
		log.debug("finding all Student instances");
		try {
			String queryString = "from Student";
			Query queryObject = session.createQuery(queryString);  //前面添加过一次之后，为什么这个getSession()又可以？
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all students failed!", re);
			throw re;
		}
	}
}
//Student stu = findById(studentId);
//stu.setTeacher(tutor);  
//session.update(stu);  //getSession()

/*public void modifyStudentById(Student persistentStu,long newStuId) {  //先查再改
session = HibernateSessionFactory.getSession();
transaction = session.beginTransaction();
log.debug("updating Student instance with new id: " + newStuId);
try {
	log.debug("update success!");
}catch (RuntimeException re) {
	log.error("update failed", re);
	throw re;
}

}*/
/*   persistentStu.setId(newStuId);
//	session.update(persistentStu);
	session.save(persistentStu);  //会出现id不同，而名字相同的两个学生  的确
	transaction.commit();
	session.close();
*/
/*public void updateId(long oldId, long newId) {  //更新主键，不能成功
session = HibernateSessionFactory.getSession();
transaction = session.beginTransaction();
log.debug("merging Teacher instance");
try {
//	session.clear();  
//	session.update(detachedInstance);  //更新学生属性
	Student stu = findById(oldId);
	stu.setId(newId);
	session.update(stu);
	log.debug("update successful");
    transaction.commit();  //直接commit即可保存
	session.close();
//	session.flush();
//	session.clear();
	} catch (RuntimeException re) {
	log.error("update failed", re);
	throw re;
}
}*/